// miniprogram/pages/classify.js
const app = getApp()
import {db} from "../../utils/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabList:[],
    currentTab:0,
    goodsList:[],
    filterGoods:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().init();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 调用getGoodsList获取数据
  getData(){
    wx.cloud.callFunction({
      name:"getGoodsList",
    }).then(res=>{
      const list = res.result.data;
      const classifys = [];
      list.forEach(el=>{
        let result = classifys.find(ev=>ev === el.classify);
        if(!result){
          classifys.push(el.classify);
        }
      });
      this.setData({
        tabList:["全部",...classifys],
        goodsList:list,
        filterGoods:list
      });

    })
  },
  // 按照类型过滤
  filterGoods(classify){
    const list = this.data.goodsList;
    if(classify === "全部"){
      this.setData({filterGoods:list});
      return
    }
    const filterGoods = list.filter(el=>el.classify === classify);
    this.setData({filterGoods});
  },
  // 切换分类
  handleSelectTab(event){
    let index = event.target.dataset.index;
    let tabLists = this.data.tabList;
    this.filterGoods(tabLists[index]);
    this.setData({
      currentTab:event.target.dataset.index
    })
  },
  // 进入商品详情
  handleSelectGoods(event){
    // console.log(event.target.dataset.item);
    const item = event.target.dataset.item;
    wx.navigateTo({
      url: '/pages/goods_detail/index?goodsId='+item.goodsId,
    })
  }
})